package com.yunnuo.system.users.service.impl;

import com.yunnuo.system.comm.util.Empty;
import com.yunnuo.system.comm.util.page.TableDataInfo;
import com.yunnuo.system.dept.dao.IDeptDao;
import com.yunnuo.system.dept.entity.Dept;
import com.yunnuo.system.dept.service.IDeptService;
import com.yunnuo.system.role.dao.IRoleDao;
import com.yunnuo.system.role.entity.Role;
import com.yunnuo.system.shiro.service.PasswordService;
import com.yunnuo.system.users.dao.IUserDao;
import com.yunnuo.system.users.dao.IUserRoleDao;
import com.yunnuo.system.users.entity.PageParams;
import com.yunnuo.system.users.entity.User;
import com.yunnuo.system.users.entity.UserRole;
import com.yunnuo.system.users.service.IUserService;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;
import java.util.regex.Pattern;
import org.springframework.data.domain.Page;
/**
 * Created by w_weihf on 2018/7/20.
 */
@Service
public class UserServiceImpl   implements IUserService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IRoleDao roleDao;
    @Autowired
    private IUserRoleDao userRoleDao;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IDeptDao  deptDao;
    @Autowired
    private PasswordService passwordService;

    @Override
    public void addVO(User vo) throws ServiceException {
        userDao.save(vo);
    }

    @Override
    public void updateVO(User user) throws ServiceException {
        String  userId = user.getId();
        if (userId!=null)
        {
            // 修改用户信息
            userDao.saveAndFlush(user);
            // 删除用户与角色关联
            userRoleDao.deleteByUserId(userId);
            // 新增用户与角色管理
            insertUserRole(user);
        }
        else
        {
            user.randomSalt();
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            // 新增用户信息
            userDao.saveAndFlush(user);
            // 新增用户与角色管理
            insertUserRole(user);
        }
    }

    @Override
    public void delList(String[] ids) throws ServiceException {
        for (String str : ids) {
            User user = userDao.findOne(str);
            if (user != null) {
                userDao.delete(user);
            }
        }
    }

    @Override
    public void deleteVo(String id) throws ServiceException {
        userDao.delete(id);
    }

    @Override
    public List<User> findList() throws ServiceException {
        return userDao.findAll();
    }

    @Override
    public List<?> findList(User vo, String other) throws ServiceException {
        return null;
    }




    @Override
    public User findVO(String id) throws ServiceException {
        return userDao.findOne(id);
    }

    @Override
    @Transactional
    public User selectUserByLoginName(String username) {
        return userDao.findAllByLoginName(username);
    }

    @Override
    public int  resetUserPwd(User user) {
        try{
            User user1 =  this.findVO(user.getId());
            user.setPassword(passwordService.encryptPassword(user1.getLoginName(),user.getPassword(),user1.getSalt()));
            return userDao.updatePasswordByUserId(user.getId(),user.getPassword());
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User selectUserById(String userId) {
        return userDao.findAllById(userId);
    }

    @Override
    public List<Role> selectRolesByUserId(String userId) {
        return roleDao.selectAllRoleByUserId(userId);
    }



    /**
     * 根据条件分页查询用户列表
     * @param pageParams
     * @return
     */
    @Override
    public TableDataInfo selectUserListByPageParams(PageParams pageParams, PageRequest pageRequest) {
        TableDataInfo dataInfo=new TableDataInfo();
        List<User> list=new ArrayList<>();
        String deptids = pageParams.getDeptId();
        List<String> ids = null ;
        if(Empty.isNotEmpty(deptids)){
            ids =  this.deptService.selectSubordinateDept(deptids);
        }
        long total=0;
        final List<String> finalIds = ids;
        Specification<User> spec = new Specification<User>() {
         @Override
         public javax.persistence.criteria.Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                String value = pageParams.getSearchValue();
                String depeid = pageParams.getDeptId();
                Path<String> namePath = root.get("realName");
                Path<String> countryPath = root.get("deptName");
                Path<String> deptId = root.get("deptId");
                // 如果查询条件不为空
                if(Empty.isNotEmpty(value)){
                    Predicate name = (cb.or(cb.like(namePath, "%"+value+"%"),cb.like(countryPath, "%"+value+"%")));
                    list.add(name);
                 }
                 // 如果部门不为空
                 if(Empty.isNotEmpty(depeid)){
                     CriteriaBuilder.In<String> in = cb.in(deptId);
                     for (String id : finalIds) {
                         in.value(id);
                     }
                     list.add(in);
                 }
                 Predicate[] p = new Predicate[list.size()];

                return cb.and(list.toArray(p));
             }
         };
         Page<User>   users= (Page<User>) userDao.findAll(spec,pageRequest);

        dataInfo.setRows(users.getContent());
        dataInfo.setTotal(users.getTotalElements());
        return dataInfo;
    }

    /**
     * 校验手机号是否唯一
     * @param user
     * @return 0-true 1-false
     */
    @Override
    public String checkPhoneUnique(User user) {
        int count=0 ;
        if(null!=user.getId()&&!"".equals(user.getId())){
            count= userDao.countAllByIdAndPhone(user.getId(),user.getPhone());
            if (count==1){
                return "0";
            }
        }
        return userDao.countUsersByPhone(user.getPhone())+"";
    }
    /**
     * 校验邮箱是否唯一
     * @param user
     * @return  0-true 1-false
     */
    @Override
    public String checkEmailUnique(User user) {
        int count=0 ;
        if(null!=user.getId()&&!"".equals(user.getId())){
            count= userDao.countAllByIdAndEmail(user.getId(),user.getEmail());
            if (count==1){
                return "0";
            }
        }
        return userDao.countAllByEmail(user.getEmail())+"";
    }

    /**
     * 保存或修改用户信息和角色
     * @param user
     * @param roleIds
     */
    @Override
    public void save(User user, String roleIds) {
        try {
            /*
                根据用户ID判断是新增还是修改，完善用户信息，更新盐
             */
            user.randomSalt();
            //如果用户ID为空，是新增
            if(user.getId()==null || "".equals(user.getId())){
                user.setCreateTime(new Date());
                user.setPassword(passwordService.encryptPassword(user.getLoginName(),user.getPassword(),user.getSalt()));
            }else{
                //如果用户ID不为空，是修改
                User thisUser=userDao.findAllById(user.getId());
                user.setLoginName(thisUser.getLoginName());
                user.setPassword(passwordService.encryptPassword(thisUser.getLoginName(),thisUser.getPassword(),user.getSalt()));
                user.setCreateTime(thisUser.getCreateTime());
            }

            /*
             * 批量上传用户时表格中填写的部门是部门名称，在这里处理
             */
            if((null==user.getDeptId() || "".equals(user.getDeptId())) &&
                    (null!=user.getDeptName() && !"".equals(user.getDeptName()))){
                Dept dept=deptDao.findAllByDeptName(user.getDeptName());
               if(Empty.isNotEmpty(dept)){
                   user.setDeptId(dept.getId());

               }

            }

            user.setUpdateTime(new Date());
            userDao.save(user);

            List<UserRole> urs=new ArrayList<>();
            String [] strs=roleIds.split(",");
            for (String roleId:strs) {
                UserRole userRole=new UserRole();
                /*
                 * 批量上传用户时表格中填写的角色是角色名称，在这里处理
                 */
                if(!Pattern.compile("^-?[1-9]\\d*$").matcher(roleId).find()){//不是数字
                    Role role=roleDao.findAllByRoleName(roleId);
                    userRole.setRoleId(role.getId());
                }else {
                    userRole.setRoleId(roleId);
                }
                userRole.setUserId(user.getId());
                urs.add(userRole);
            }
            userRoleDao.deleteByUserId(user.getId());
            userRoleDao.save(urs);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 校验用户登录名唯一
     * @param user
     * @return 0-成功  1-失败
     */
    @Override
    public String checkLoginNameUnique(User user) {
        int count=0 ;
        if(null!=user.getId()&&!"".equals(user.getId())){
            count= userDao.countAllByIdAndLoginName(user.getId(),user.getLoginName());
            if (count==1){
                return "0";
            }
        }
        return userDao.countAllByLoginName(user.getLoginName())+"";
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(User user)
    {
        // 新增用户与角色管理
        List<UserRole> list = new ArrayList<UserRole>();
        for (String roleId : user.getRoleIds())
        {
            UserRole ur = new UserRole();
            ur.setUserId(user.getId());
            ur.setRoleId(roleId);
            userRoleDao.saveAndFlush(ur);
        }

    }
}
